<template>
  <div>
    <div class="buttonGroup">
      <el-button v-if="form.id && !disabled" @click="update">更 新</el-button>
      <el-button v-if="!form.id && !disabled" @click="save(false)"
        >保 存</el-button
      >
      <el-button type="info" :icon="Close" @click="reback(true)"
        >退 出</el-button
      >
    </div>
    <el-scrollbar :height="h">
      <el-form
        :model="form"
        label-position="right"
        ref="formRef"
        :rules="formRules"
        :class="{ borderNone: disabled }"
        :disabled="disabled"
      >
        <ts-card header="基本信息">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="销售合同" required>
                <ts-select
                  v-if="!disabled"
                  v-model="form.omOrderId"
                  :label="form.omOrderNo"
                  fileName="WaitCovertOrderDtlReport"
                  :template="omOrderTemplate"
                  :mapping="omOrderMapping"
                  @updateRow="updateOmOrder"
                ></ts-select>
                <span v-else>{{ form.omOrderNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="供应商" required>
                <ts-select
                  v-if="!disabled"
                  v-model="form.supplierId"
                  :label="form.supplierName"
                  fileName="SupplierReport"
                  :template="supplierTemplate"
                  :mapping="supplierMapping"
                  @updateRow="updateSupplier"
                ></ts-select>
                <span v-else>{{ form.supplierName }}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="采购方" required>
                <ts-select
                  v-if="!disabled"
                  v-model="form.buyerId"
                  :label="form.buyerName"
                  fileName="CompanyReport"
                  :template="buyerTemplate"
                  :mapping="buyerMapping"
                  @updateRow="updateMore"
                ></ts-select>
                <span v-else>{{ form.buyerName }}</span>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="供应商名称" require>
                <el-input
                  placeholder="供应商名称"
                  v-model="form.supplierName"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="供应商地址" require>
                <el-input
                  placeholder="供应商地址"
                  v-model="form.supplierAddress"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="供应商电话" require>
                <el-input
                  placeholder="供应商电话"
                  v-model="form.supplierPhone"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="供应商传真" require>
                <el-input
                  placeholder="供应商传真"
                  v-model="form.supplierFax"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </ts-card>
        <ts-card header="订单信息">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="采购单号" required>
                <el-input v-model="form.number">
                  <template v-if="!disabled && form.supplierId" #append>
                    <el-button :icon="Refresh" @click="getNumber" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
              <el-form-item label="采购日期" required>
                <el-date-picker
                  v-model="form.purchaseDate"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
              <el-form-item label="交货日期" required>
                <el-date-picker
                  v-model="form.deliveryTime"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="付款方式">
                <el-input v-model="form.payMethod"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
              <el-form-item label="采购员" required>
                <ts-select
                  v-if="!disabled"
                  v-model="form.purchaserId"
                  :label="form.purchaserName"
                  :template="purchaserTemplate"
                  file-name="ChooseEmployeeReport"
                ></ts-select>
                <span v-else>{{ form.purchaserName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="其它备注" require>
                <el-input v-model="form.remark" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </ts-card>

        <ts-card header="订单细项">
          <sc-form-table
            v-model="dataList"
            dragSort
            onlyDelete
            @delete="rowDelete"
            placeholder="暂无数据"
            rowKey="mtlId"
          >
            <template #tableContent>
              <el-table-column label="订单产品英文名" width="300">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.mtlEnName"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="产品中文名" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.mtlName"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="订舱英文名" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.bookingSpaceEnName"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="包装规格"
                prop="mtlSpec"
                width="100"
              ></el-table-column>
              <el-table-column label="报关中文名" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.customsDeclarationName"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="外销数量"
                prop="omOrderDtlQty"
                width="120"
              >
              </el-table-column>
              <el-table-column
                label="销售单位"
                prop="omMtlUnitName"
                width="120"
              ></el-table-column>
              <el-table-column label="含进仓费" width="120">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.includeWarehouseFees"
                    clearable
                    placeholder="请选择："
                  >
                    <el-option
                      v-for="item in configData.includeWarehouseFeesList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="采购数量" width="120">
                <template #default="scope">
                  <el-input-number
                    style="width: 95%; padding: 0px"
                    v-model="scope.row.qty"
                    :max="getMax(scope.row)"
                    @change="handlePrice(scope.row)"
                    controls-position="right"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="采购单位"
                prop="mtlUnitName"
                width="120"
              ></el-table-column>
              <el-table-column label="包装要求" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.packing"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="采购单价" width="120">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.price"
                    type="number"
                    @change="handlePrice(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="采购总价"
                prop="totalAmount"
                width="120"
              ></el-table-column>
              <el-table-column
                label="件数"
                prop="pieces"
                width="120"
              ></el-table-column>
              <el-table-column label="长" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.length" type="number" @change="handleVolume(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="宽" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.width" type="number" @change="handleVolume(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="高" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.high" type="number" @change="handleVolume(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="体积"
                prop="volume"
                width="120"
              ></el-table-column>
              <el-table-column label="单位毛重" width="120">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.grossWeight"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单位净重" width="120">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.netWeight"
                    type="number"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="样品备注" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.remark"
                    type="textarea"
                  ></el-input>
                </template>
              </el-table-column>
            </template>
            <template #append>
              <div style="display: flex; background-color: #fff1d4">
                <div style="display: flex; padding: 8px 0">
                  <div class="sum_footer_unit" style="width: 1480px">合计</div>
                  <div class="sum_footer_unit" style="width: 560px">
                    {{ form.totalQty }}
                  </div>
                  <div class="sum_footer_unit">
                    {{ form.totalAmount }}
                  </div>
                </div>
              </div>
            </template>
          </sc-form-table>
        </ts-card>
      </el-form>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed ,watch} from "vue";
import { ElNotification } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { Refresh, Plus, Close } from "@element-plus/icons-vue";
import Api from "@/api/model/om";
import tsSelect from "@/components/scSelect/index.vue";
import { deepClone } from "@/utils/arr";
import useTabs from "@/utils/useTabs";
import tool from "@/utils/tool";
const emit = defineEmits(["updatetable"]);
const route = useRoute();
const router = useRouter();
const props = defineProps({
  paramsData: {
    type: Object,
    defalut: {},
  },
});
const h = computed(() => {
  let height;
  var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  if (!iOS) {
    height = window.innerHeight;
  } else {
    height = screen.height;
  }
  return height - 150;
});
const omOrderTemplate = {
  label: "omOrderNo",
  value: "omOrderId",
};
const supplierTemplate = {
  label: "supplierName",
  value: "supplierId",
};
const buyerTemplate = {
  label: "buyerName",
  value: "buyerId",
};
const purchaserTemplate = {
  value: "id",
  label: "name",
};
// 添加用户数据的对象
const form = ref({});
const copyForm = ref({});
const disabled = ref(false);
const configData = ref([]);
const formRef = ref();
const formRules = reactive({});
const dataList = ref([]);
const deleteDataList = ref([]);
const supplierMapping = [
  { value: "id", label: "supplierId" },
  { value: "corpAddress", label: "supplierAddress" },
  { value: "name", label: "supplierName" },
  { value: "corpPhone", label: "supplierPhone" },
  { value: "corpFax", label: "supplierFax" },
  { value: "payMethod", label: "payMethod" },
];
const omOrderMapping = [
  { value: "number", label: "omOrderNo" },
  { value: "id", label: "omOrderId" },
  { value: "address", label: "sellerAddress" },
  { value: "contactPhone", label: "sellerPhone" },
];
const buyerMapping = [
  { value: "id", label: "buyerId" },
  { value: "name", label: "buyerName" },
];
const optType = ref();
watch(dataList, (newValue, oldValue) => {
  form.value.totalQty = dataList.value.reduce(
    (sum, e) => sum + Number(e.qty || 0),
    0
  );
  form.value.totalAmount = tool.formatRoundNum(
    dataList.value.reduce((sum, e) => sum + Number(e.totalAmount || 0), 0),
    2
  );
}, { deep: true })
onMounted(() => {
  optType.value = route.query.optType;
  console.log(route.query);
  // if (route.query.rowIds || route.query.id) {
    getInit();
  // }
});
const getInit = async (val) => {
  if (optType.value === "detail") {
    disabled.value = true;
  }
  let res;
  let param = val ? val : route.query ||'';
  if (optType.value === "add") {
    res = await Api.poOrder.add.post(param);
  } else {
    res = await Api.poOrder.detail.post(param);
  }
  if (res.code == "200") {
    configData.value = res.configData;
    form.value = deepClone(res.data);
    dataList.value = res.dataList||[];
  }
};
const updateOmOrder = async (val) => {
  copyForm.value = deepClone(form.value);
  form.value = val;
  form.value = Object.assign(deepClone(copyForm.value), form.value);
  getInit({ id: val.omOrderId });
};
const getNumber = async () => {
  let res = await Api.poOrder.generatePoOrderNo.post({
    id: form.value.supplierId,
  });
  if (res.code === "200") {
    form.value.number = res.number;
  }
};
const updateMore = (val) => {
  copyForm.value = deepClone(form.value);
  form.value = val;
  form.value = Object.assign(deepClone(copyForm.value), form.value);
};
const updateSupplier = (val) => {
  copyForm.value = deepClone(form.value);
  form.value = val;
  form.value = Object.assign(deepClone(copyForm.value), form.value);
  getNumber();
};
const rowDelete = (val) => {
  deleteDataList.value.push(val);
};
const getMax = (row) => {
  return row.omOrderDtlQty - row.convertedPoQty;
};
const handlePrice = (row) => {
  row.pieces = tool.formatRoundNum(row.qty / row.mtlSpec, 1);
  row.totalAmount = tool.formatRoundNum(row.price * row.qty, 2);

};
const handleVolume = (row)=>{
  row.volume = tool.formatRoundNum(row.length *row.width*row.high, 3)
}
const save = async (val) => {
  let param = {
    bean: form.value,
    dataList: dataList.value,
  };
  console.log(param);
  let res = await Api.poOrder.save.post(param);
  console.log(res);
  if (res.code == "200") {
    optType.value = "save";
    ElNotification.success({
      title: "",
      message: "添加成功！",
      duration: 2000,
    });
    reback();
    // if (val) {
    //     getInit(false);
    // } else {
    //     getInit({id:res.id});
    // }
  }
};
const update = async () => {
  let param = {
    bean: form.value,
    dataList: dataList.value.concat(deleteDataList.value),
  };
  console.log(param)
  let res = await Api.poOrder.update.post(param);
  if (res.code == "200") {
    ElNotification.success({
      title: "",
      message: "更新成功！",
      duration: 2000,
    });
    reback();
    // getInit({id:res.id});
  }
};
const reback = () => {
  useTabs.close();
  router.back();
  router.push({
    path: "/poorder/PoOrderReport",
    // query: {
    //     isRefresh: true,
    // },
  });
  route.isRefrensh = true;
};
</script>
<style lang="less" scoped>
.buttonGroup {
  align-items: center;
  box-sizing: border-box;
  display: flex;
  height: 48px;
  justify-content: flex-end;
  margin-bottom: 12px;
  padding: 10px 16px;
  font-size: 12px;
  list-style-type: none;
  text-align: left;
  background-color: #ffffff;
}

.borderNone {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
      inset;
    cursor: default;
    background-color: transparent; //背景颜色透明
    border-bottom: 1px solid #999;
    border-radius: 0;

    .el-input__inner {
      cursor: default !important;
    }
  }

  :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
      inset;
    cursor: default;
    background-color: transparent; //背景颜色透明
    border-bottom: 1px solid #999;
    border-radius: 0;
  }
}

.sum_footer_unit {
  height: 23px;
  line-height: 23px;
  padding: 0 12px;
  font-size: 14px;
  font-weight: 600;
  text-align: left;
}
:deep(.el-input-number__increase) {
  display: none;
}
:deep(.el-input-number__decrease) {
  display: none;
}
:deep(.el-input-number .el-input__wrapper) {
  padding: 0px;
}
</style>